package com.tiance.web.filter;

import com.tiance.common.ServiceContext;
import com.tiance.common.ServiceContextHolder;
import com.tiance.constants.CommonConstants;
import com.tiance.utils.EnvironmentUtil;
import com.tiance.utils.SessionUtil;
import com.tiance.web.utils.AccessUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "*.htm", filterName = "serviceContextFilter")
public class ServiceContextFilter extends OncePerRequestFilter {

    private static Logger logger = LoggerFactory.getLogger(ServiceContextFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        final Long timeStart = System.currentTimeMillis();//开始计时
        MDC.put(CommonConstants.MDC_KEY, SessionUtil.getSessionId());
//        AccessUtil.recordAccessLog(request);
        ServiceContext sc = new ServiceContext();
        Boolean refererOrIp = AccessUtil.validateIsUserSubmit(request);
        logger.info("本次请求验证记：[{}]", refererOrIp ? "referer" : "ip");
        sc.setClientIp(EnvironmentUtil.getIP(request));//设置IP
        ServiceContextHolder.set(sc);

        try {
            // 设置线程变量,通过 dubbo传递 traceid
            filterChain.doFilter(request, response);
        } finally {
            ServiceContextHolder.cleanUp();
            // 清理线程变量
            MDC.clear();
            Long timeCost = System.currentTimeMillis() - timeStart;
            logger.info("time cost=[{}]", new Object[] { timeCost });
        }
    }



}
